﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Tsanie.AzerothReader;
using System.Windows.Forms;

namespace Tsanie.AzerothReader.Util {
    class LogUtil {
        private static StreamWriter _logWriter = null;

        static LogUtil() {
            _logWriter = new StreamWriter(Config.c_AppPath + @"\\Tsanie.AzerothReader.log", true, Encoding.UTF8);
        }
        public static void Error(Exception ex, Action<Exception> exFunc) {
            if (Config.LogError)
                WriteError(ex, 0);
            if (exFunc != null)
                exFunc(ex);
        }
        private static void WriteError(Exception ex, int indent) {
            if (ex == null)
                return;
            if (indent > 0) {
                _logWriter.Write('└');
                _logWriter.Write(new string('─', indent));
            }
            _logWriter.WriteLine("--------------------------------------------------");
            _logWriter.WriteLine("[{0}] - {1}: {2}", DateTime.Now.ToString("MM-dd HH:mm:ss"), ex.GetType().FullName, ex.Message);
            _logWriter.WriteLine("--------------------------------------------------");
            _logWriter.WriteLine(ex.StackTrace);
            _logWriter.WriteLine();
            _logWriter.Flush();
            if (ex.InnerException != null)
                WriteError(ex.InnerException, indent + 1);
        }
    }

    static class TaskbarExt {
        public static void SetState(this ITaskbarList3 taskbar, IntPtr handle, TBPFLAG state) {
            if (taskbar != null)
                taskbar.SetProgressState(handle, state);
        }
        public static void SetValue(this ITaskbarList3 taskbar, IntPtr handle, int completed, int total) {
            if (taskbar != null)
                taskbar.SetProgressValue(handle, (ulong)completed, (ulong)total);
        }
    }

    static class ControlExt {
        public static void ThreadSafeRun(this Control c, MethodInvoker m) {
            try {
                if (c != null && c.InvokeRequired)
                    c.Invoke(m);
                else
                    m();
            } catch (Exception ex) {
                LogUtil.Error(ex, null);
            }
        }
        public static void ThreadSafeRunBegin(this Control c, MethodInvoker m) {
            try {
                if (c != null && c.InvokeRequired)
                    c.BeginInvoke(m);
                else
                    m();
            } catch (Exception ex) {
                LogUtil.Error(ex, null);
            }
        }
    }
}
